// pages/bursting_chains/index.js
var app = getApp(); //引用app.js
var commonURL = app.data.baseURL;
var commonURLYY = app.data.newURL;
var commonURLXX = app.data.lastURL;
var baseURL1 = app.data.baseURL;
var jielong = app.data.jielong;
var jlpay = app.data.jlpay;
var promise1 = null;
var promise2 = null;
var promise3 = null;
var promise4 = null;
var promise5 = null;
var promise6 = null;
var canvasCtx = '';
var formid = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num: [],
    lasttimestamp: 2,
    count: 40,
    getShow: false,
    dataList: null,
    ptime: [],
    isover: false,
    formid: [],
    isblock: false
  },
  toReduce: function(event) {
    console.log(event)
    formid.push(event.detail.formId)
    var nums = event.detail.target.dataset.num;
    if (nums > 0) {
      var index = event.detail.target.dataset.index;
      var num = this.data.num;
      num[index] = nums - 1;
      this.setData({
        num: num,
      })
      var arr = this.data.goods[index];
      arr.num = nums - 1;
      var list = [];
      if (nums - 1 == 0) {
        var goodsArr = wx.getStorageSync('goodsArr')
        for (var i = 0; i < goodsArr.length; i++) {
          if (goodsArr[i].id != this.data.goods[index].id) {
            list.push(goodsArr[i])
          }
        }
        console.log(list)
        wx.setStorage({
          key: 'goodsArr',
          data: list,
        })
      } else {
        this.saveStorage(arr);
      }
    } else {
      wx.showToast({
        title: '不能再减啦',
        icon: 'none'
      })
    }
  },
  getinfo: function(areaid, tzinfo) {
    var that = this;
    wx.request({
      url: commonURL + 'op=automatic',
      data: {
        openid: wx.getStorageSync('openid'),
        areaid: areaid
      },
      success: function(res) {
        console.log(res)
        if (res.data.status == 0) {
          that.iscommer()
          console.log('绑定111')
        } else if (res.data.status == 1) {
          console.log('绑定成功')
          console.log(res)
          console.log(tzinfo)
          wx.setStorage({
            key: 'tzInfo',
            data: tzinfo,
          })
          that.setData({
            tzInfo: tzinfo
          })
        }
      },
      fail: function(res) {
        console.log('99')
        console.log(res)
      }
    })
  },
  previewImg: function(e) {
    console.log(e)
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: this.data.homeimg // 需要预览的图片http链接列表
    })
  },
  previewad: function(e) {
    console.log(e)
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: this.data.banner // 需要预览的图片http链接列表
    })
  },
  onPullDownRefresh: function() { //页面下拉加载首页数据
    this.onLoad()
  },
  toPlus: function(event) {
    console.log(1)
    formid.push(event.detail.formId);
    var status = this.data.status;
    var nums = event.detail.target.dataset.num;
    nums = parseInt(nums);
    var num = this.data.num;
    var index = event.detail.target.dataset.index;
    var starttime = Number(this.data.startline)
    var totalSecond = starttime - Date.parse(new Date()) / 1000;
    totalSecond = 1;
    console.log(totalSecond)
    if (status == '1') {
      // if (totalSecond <= 0) {
      if (this.data.goods[index].gnum == 0) {
        wx.showToast({
          title: '该商品已售完',
          icon: 'none'
        })
        return;
      }
      if (nums + 1 > this.data.goods[index].gnum) {
        wx.showToast({
          title: '该商品库存被抢完啦',
          icon: 'none'
        })
        return;
      }
      //单次限购
      if (this.data.goods[index].one_limit == 0) {
        if (nums > 0) {
          wx.showToast({
            title: '该商品单次限购1件',
            icon: 'none'
          })
          return;
        }
      } else {
        if (nums + 1 > Number(this.data.goods[index].one_limit)) {
          wx.showToast({
            title: '该商品单次已限购' + this.data.goods[index].one_limit + '件',
            icon: 'none'
          })
          return;
        }
      }
      //总限购
      if (this.data.goods[index].many_limit == 0) {
        if (nums > 999999) {
          wx.showToast({
            title: '该商品已达到总限购数量',
            icon: 'none'
          })
          return;
        }
      } else {
        console.log(nums + 1 + Number(this.data.goods[index].historynum), Number(this.data.goods[index].many_limit))
        if (nums + 1 + Number(this.data.goods[index].historynum) > Number(this.data.goods[index].many_limit)) {
          wx.showToast({
            title: '该商品已达到总限购数量' + this.data.goods[index].many_limit + '件',
            icon: 'none'
          })
          return;
        }
      }
      num[index] = nums + 1;
      console.log(nums)
      this.setData({
        num: num,
      })
      var arr = this.data.goods[index];
      arr.num = nums + 1;
      this.saveStorage(arr);
      wx.setStorage({
        key: 'selectid',
        data: this.data.id,
      })
    } else if (status == '2') {
      wx.showToast({
        title: '活动结束啦',
        icon: 'none'
      })
    } else if (status == '0') {
      wx.showToast({
        title: '活动还未开始',
        icon: 'none'
      })
    }
  },
  escapeHtml: function(text) {
    var a = text.replace(/(\&lt;)/g, "<");
    var b = a.replace(/(\&gt;)/g, ">");
    var c = b.replace(/(\&amp;)/g, "\&");
    var d = c.replace(/(\&quot;)/g, "\"");
    return d;
  },
  timeChange: function(timestamp) {
    var arrTimestamp = (timestamp + '').split('');
    for (var start = 0; start < 13; start++) {
      if (!arrTimestamp[start]) {
        arrTimestamp[start] = '0';
      }
    }
    timestamp = arrTimestamp.join('') * 1;

    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - timestamp;

    // 如果本地时间反而小于变量时间
    if (diffValue < 0) {
      return '不久前';
    }

    // 计算差异时间的量级
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;

    // 数值补0方法
    var zero = function(value) {
      if (value < 10) {
        return '0' + value;
      }
      return value;
    };
    // 使用
    if (monthC > 12) {
      // 超过1年，直接显示年月日
      return (function() {
        var date = new Date(timestamp);
        return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
      })();
    } else if (monthC >= 1) {
      return parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
      return parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
      return parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
      return parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
      return parseInt(minC) + "分钟前";
    }
    return '刚刚';

  },
  saveStorage: function(val) {
    var goodsArr;
    var that = this;
    wx.getStorage({
      key: 'goodsArr',
      success: function(res) {
        goodsArr = res.data;
        that.setStorage(goodsArr, val);
      },
      fail: function(res) {
        goodsArr = [];
        that.setStorage(goodsArr, val);
      },
    })
  },
  setStorage: function(goodsArr, val) {
    if (goodsArr.length > 0) {
      var i = 0;
      for (i = 0; i < goodsArr.length; i++) {
        console.log(goodsArr[i].id == val.id);
        if (goodsArr[i].id == val.id) {
          goodsArr.splice(i, 1, val);
          break;
        }
      }
      if (i == goodsArr.length) {
        goodsArr.push(val);
      }
    } else {
      goodsArr.push(val);
    }
    wx.setStorage({
      key: 'goodsArr',
      data: goodsArr,
    })
  },
  downfile(url) { //下载网络图片的promise对象
    return new Promise(function(resolve, reject) {
      wx.downloadFile({
        url: url,
        success: function(res) {
          resolve(res.tempFilePath)
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    console.log(options)
    var id = '';
    var status = null;
    var area_id = '';
    promise1 = this.downfile('https://www.lexiangpingou.cn/addons/lexiangpingou/app/resource/images/xcxjl/share2.png');
    that.setData({
      promise1: promise1
    })
    // wx.downloadFile({
    //   url: ,
    //   success: function (res) {
    //     that.setData({
    //       sharebg: res.tempFilePath
    //     })
    //     console.log('下载好了1')
    //   },
    //   fail: function (res) {
    //     console.log('22' + res)
    //   }
    // })
    if (decodeURIComponent(options.scene) !== 'undefined') {
      let scene = decodeURIComponent(options.scene);
      // id + '&' + status + '&' + wx.getStorageSync('tzInfo').area_id
      id = scene.split("&")[0];
      status = scene.split('&')[1];
      area_id = scene.split('&')[2];
      wx.setStorage({
        key: 'selectAreaid',
        data: area_id,
      })
      that.setData({
        id: id,
        status: status
      })
      wx.request({
        url: baseURL1 + 'op=teaminfo',
        data: {
          areaid: area_id,
          uniacid: app.data.GZHid
        },
        success: function(res) {
          if (res.data.status == 1) {
            that.getinfo(area_id, res.data.data)
          } else {
            wx.showToast({
              title: '获取团长信息失败',
            })
          }
        }
      })
      wx.getStorage({
        key: 'userInfo',
        success: function(res) {},
        fail: function(res) {
          wx.redirectTo({
            url: '../../welcome/welcome',
          })
        }
      })
    } else if (options.activeid) {
      var tzInfo = JSON.parse(options.tzInfo)
      console.log('信息' + tzInfo.area_id)
      id = options.activeid
      var areaid = tzInfo.area_id
      status = options.activestatus
      wx.setStorage({
        key: 'selectAreaid',
        data: areaid,
      })
      this.getinfo(areaid, tzInfo)
      promise2 = this.downfile(tzInfo.avatar)
      that.setData({
        promise2: promise2
      })
      // wx.downloadFile({
      //   url: tzInfo.avatar,
      //   success: function (res) {
      //     that.setData({
      //       TzImg: res.tempFilePath
      //     })
      //   },
      //   fail: function (res) {
      //     console.log('团长' + res)
      //   }
      // })
      that.setData({
        id: id,
        status: status,
        noright: false
      })
      wx.getStorage({
        key: 'userInfo',
        success: function(res) {},
        fail: function(res) {
          wx.redirectTo({
            url: '../../welcome/welcome',
          })
        }
      })
    } else {
      var homeimg = JSON.parse(options.img)
      that.setData({
        homeimg: homeimg,
        startline: options.time
      })
      id = options.id;
      status = options.status;
      that.setData({
        id: id,
        status: status
      })
    }
    wx.request({
      url: baseURL1 + 'op=getWXACodeUnlimit',
      data: {
        appid: app.data.appid,
        secret: app.data.secret,
        uniacid: app.data.GZHid,
        opneid: app.data.openid || wx.getStorageSync('openid'),
        page: 'pages/jielong/products/products',
        dev: 1,
        scene: id + '&' + status + '&' + wx.getStorageSync('tzInfo').area_id
      },
      success: function(res) {
        console.log(res)

        promise3 = that.downfile(res.data.data.surl)
        that.setData({
          promise3: promise3
        })
        // wx.downloadFile({
        //   url: res.data.data.surl,
        //   success: function (res) {
        //     that.setData({
        //       qrcodeImg11: res.tempFilePath
        //     })
        //   },
        //   fail: function (res) {
        //     console.log('44' + res)
        //     console.log(res)
        //   }
        // })
      }
    })
    wx.request({
      url: jlpay + 'op=getOrderList',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        uniacid: app.data.GZHid,
        activeid: Number(id),
        currenttimestamp: Math.round(new Date() / 1000),
        page: 1,
        count: that.data.count,
      },
      success: function(res) {
        console.log(res)
        if (res.data.status) {
          that.setData({
            dataList: res.data.data
          }, () => {
            //数据太少 等数据多了再做分页
            console.log(that.data.dataList)
            let arr = []
            let date = Math.floor(Math.round(new Date() / 1000))
            for (let i = 0; i < that.data.dataList.length; i++) {
              arr.push(that.timeChange(that.data.dataList[i].ptime))
              // arr[i]=0
            }
            // console.log(arr)
            // let lengthtime = that.data.dataList.length-1
            that.setData({
              // lasttimestamp: ,
              ptime: arr
            }, () => {
              console.log(that.data.ptime)
            })
          })
        }
      }
    })
    wx.request({
      url: jielong + 'action=getBanner',
      data: {
        uniacid: app.data.GZHid
      },
      method: 'POST',
      success: function(res) {
        var banner = [];
        for (var i = 0; i < res.data.data.length; i++) {
          banner.push(res.data.data[i].thumb)
        }
        that.setData({
          banner: banner
        })
      }
    })
    wx.request({
      url: baseURL1 + 'op=homeinfo',
      data: {
        unionId: app.data.unionId || wx.getStorageSync('unionId'),
        activeing: id,
        openid: wx.getStorageSync('openid')
      },
      success: function(res) {
        console.log(res)
        var isover = [];
        var goodimglist = [];
        for (var i = 0; i < res.data.commodity.length; i++) {
          if (res.data.commodity[i].goodsdesc != null) {
            res.data.commodity[i].goodsdesc = that.escapeHtml(res.data.commodity[i].goodsdesc)
          }
          if (res.data.commodity[i].gnum == 0) {
            isover.push(true)
          } else {
            isover.push(false)
          }
        }
        promise4 = that.downfile(res.data.activelist.imgurl2[0].imgurl)
        promise5 = that.downfile(res.data.activelist.imgurl2[1].imgurl)
        promise6 = that.downfile(res.data.activelist.imgurl2[2].imgurl)
        // for (var i = 0; i < res.data.activelist.imgurl2.length; i++) {
        //   if (i > 2) {
        //     break
        //   }
        //     var a = i;
        //     console.log(a)            
        // }
        // for (var i = 0; i < res.data.activelist.imgurl2.length; i++) {
        //   if (i > 2) {
        //     break
        //   }
        //   wx.downloadFile({
        //     url: res.data.activelist.imgurl2[i].imgurl,
        //     success: function (res) {
        //       console.log(res)
        //       goodimglist.push(res.tempFilePath)
        //       that.setData({
        //         goodimglist: goodimglist
        //       })
        //     },
        //     fail: function (res) {
        //       console.log('活动' + res)
        //     }
        //   })
        // }
        console.log(isover)
        that.setData({
          isover: isover,
          business: res.data.business
        })
        console.log(res)
        var num = [];
        console.log(res)
        let time = Math.floor(Math.round(new Date() / 1000))
        for (var i = 0; i < res.data.commodity.length; i++) {
          num.push("0");
        }
        that.setData({
          goods: res.data.commodity,
          num: num,
          time: that.timeChange(res.data.activelist.startline),
          activelist: res.data.activelist
        })
        // wx.downloadFile({
        //   url: res.data.activelist.imgurl,
        //   success: function (res) {
        //     that.setData({
        //       shareactiveImg: res.tempFilePath
        //     })
        //   },
        //   fail: function (res) {
        //     console.log('33' + res)
        //   }
        // })
        if (that.data.status == '1') {
          console.log('222')
          wx.getStorage({
            key: 'goodsArr',
            success: function(res) {
              var goodsArr = res.data;
              var goods = that.data.goods;
              var num = that.data.num;
              for (var i = 0; i < goodsArr.length; i++) {
                for (var j = 0; j < goods.length; j++) {
                  if (goodsArr[i].id == goods[j].id) {
                    num[j] = goodsArr[i].num;
                    continue;
                  }
                }
                // if (goodsArr[i].activeid!=)
              }
              that.setData({
                num: num,
              })
            },
          });

        }
      }
    })
    wx.getStorage({
      key: 'isTz',
      success: function(res) {
        console.log(res)
        if (res.data == 1) {
          that.setData({
            isTz: true
          })
        } else {
          that.setData({
            isTz: false
          })
        }

      },
    });
    wx.getStorage({
      key: 'business',
      success: function(res) {
        if (res.data.address.length > 0) {
          that.setData({
            businessaddress: res.data.address[0].storename
          })

        }
      },
    });
    wx.getStorage({
      key: 'noright',
      success: function(res) {
        that.setData({
          noright: res.data
        })
      },
    })
    wx.getStorage({
      key: 'tzInfo',
      success: function(res) {
        console.log(res)
        promise2 = that.downfile(res.data.avatar)
        that.setData({
          promise2: promise2
        })
        // wx.downloadFile({
        //   url: res.data.avatar,
        //   success: function(res) {
        //     that.setData({
        //       TzImg: res.tempFilePath
        //     })
        //   },
        //   fail: function(res) {
        //     console.log(res)
        //   }
        // })
        if (res.data != '') {
          that.setData({
            tzInfo: res.data
          })
        }
      },
    });

    // wx.getStorage({
    //   key: 'product',
    //   success: function(res) {
    //     that.setData({
    //       product: res.data
    //     });
    //     console.log(res)
    //     var goodimglist = []

    //     console.log(goodimglist)


    //   },
    // });
  },
  iscommer: function() {
    var that = this;
    wx.request({ //获取是否团长
      url: commonURL + 'op=is_area_commander_copy',
      data: {
        "openid": wx.getStorageSync('openid'),
        "uniacid": app.data.GZHid,
        'unionId': app.data.unionId || wx.getStorageSync('unionId')
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        console.log(res)
        if (res.data != '') {
          if (res.data.status == 1) {
            console.log('设置团长1')
            wx.setStorage({
              key: 'tzInfo',
              data: res.data.team,
            })
            wx.setStorage({
              key: 'isTz',
              data: 1,
            })
            wx.setStorage({
              key: 'noright',
              data: false,
            })
            that.setData({
              tzInfo: res.data.team,
            })
          } else if (res.data.status == 2) {
            console.log('设置团长2')
            wx.setStorage({
              key: 'isTz',
              data: 0,
            })
            wx.setStorage({
              key: 'noright',
              data: false,
            })
            wx.setStorage({
              key: 'tzInfo',
              data: res.data.team,
            })
            that.setData({
              tzInfo: res.data.team,
            })
          } else {
            wx.setStorage({
              key: 'isTz',
              data: 0,
            })
            wx.setStorage({
              key: 'noright',
              data: true,
            })
            wx.setStorage({
              key: 'tzInfo',
              data: '',
            })
          }
        } else {
          wx.showToast({
            title: '请重新授权',
            icon: 'none'
          })
        }
      }
    })
  },
  gogroup: function() {
    wx.navigateTo({
      url: '../member_list/member_list',
    })
  },
  godetail: function(e) {
    console.log(e)
    wx.setStorage({
      key: 'detail',
      data: e.currentTarget.dataset.detail,
      success: function(res) {
        wx.navigateTo({
          url: '../gooddetail/gooddetail?status=' + e.currentTarget.dataset.status,
        })
      },
      fail: function() {
        console.log(res)
      }
    })
  },
  goshare: function() {
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  gocart: function(event) {
    console.log(1)
    var that = this;
    that.setData({
      isblock: true
    })
    var starttime = Number(this.data.startline)
    var totalSecond = starttime - Date.parse(new Date()) / 1000;
    // if (totalSecond <= 0) {
    formid.push(event.detail.formId)
    var goodlist = [];
    for (var i = 0; i < wx.getStorageSync('goodsArr').length; i++) {
      if (wx.getStorageSync('goodsArr')[i].activeid == that.data.id) {
        for (var j = 0; j < that.data.goods.length; j++) {
          if (wx.getStorageSync('goodsArr')[i].id == that.data.goods[j].id && that.data.goods[j].gnum != 0) {
            goodlist.push(wx.getStorageSync('goodsArr')[i])
          }
        }
      }
    }
    wx.setStorage({
      key: 'goodsArr',
      data: goodlist,
      success: function(res) {
        console.log(wx.getStorageSync('goodsArr').length)
        if (wx.getStorageSync('goodsArr').length == 0) {
          wx.showToast({
            title: '请选择商品',
          })
          that.setData({
            isblock: false
          })
          return;
        } else {
          var activeid = wx.getStorageSync('goodsArr')[0].activeid;
          wx.request({
            url: jielong + 'action=checkAction',
            data: {
              uniacid: app.data.GZHid,
              id: activeid
            },
            method: "POST",
            success: function(res) {
              console.log(res)
              if (res.data.status == 1) {
                wx.navigateTo({
                  url: '../creatorder/creatorder',
                })
                wx.setStorage({
                  key: 'formid',
                  data: formid,
                })
              } else {
                var num = [];
                for (var i = 0; i < that.data.num.length; i++) {
                  num.push(0)
                }
                wx.showModal({
                  title: '提示',
                  showCancel: false,
                  content: res.data.data,
                  complete: function(res) {
                    wx.setStorage({
                      key: 'goodsArr',
                      data: [],
                    })
                    that.setData({
                      num: num
                    })
                  }
                })
              }
              that.setData({
                isblock: false
              })
            },
            fail: function(res) {
              that.setData({
                isblock: false
              })
            }
          })
        }
      },
      fail: function(res) {
        console.log(res)
        that.setData({
          isblock: false
        })
      }
    })
    // } else {
    //   wx.showToast({
    //     title: '活动还未开始呢',
    //     icon: 'none'
    //   })
    //   that.setData({
    //     isblock: false
    //   })
    // }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.showLoading({
      title: '加载中',
    })
    setTimeout(function() {
      wx.hideLoading()
    }, 1000)
    var that = this;
    var num = that.data.num;
    formid = [];
    if (that.data.status == 1) {
      wx.getStorage({
        key: 'goodsArr',
        success: function(res) {

          var goodsArr = res.data;
          var goods = that.data.goods;
          var num = that.data.num;
          if (res.data.length == 0) {
            for (var i = 0; i < num.length; i++) {
              num[i] = 0;
            }
          } else {
            for (var i = 0; i < goodsArr.length; i++) {
              for (var j = 0; j < num.length; j++) {
                if (goodsArr[i].id == goods[j].id) {
                  num[j] = goodsArr[i].num;
                  continue;
                }
              }
            }
          }

          that.setData({
            num: num,
          })
        },
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this
    wx.getStorage({
      key: 'tzInfo',
      success: function(res) {
        console.log(res)
        promise2 = that.downfile(res.data.avatar)
        that.setData({
          promise2: promise2
        })
        // wx.downloadFile({
        //   url: res.data.avatar,
        //   success: function(res) {
        //     that.setData({
        //       TzImg: res.tempFilePath
        //     })
        //   },
        //   fail: function(res) {
        //     console.log('11' + res)
        //   }
        // })
        if (res.data != '') {
          that.setData({
            tzInfo: res.data
          })
        }
      },
    });
    wx.getStorage({
      key: 'product',
      success: function(res) {
        that.setData({
          product: res.data
        });
        wx.request({
          url: jlpay + 'op=getOrderList',
          method: 'POST',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            uniacid: app.data.GZHid,
            activeid: Number(res.data.id),
            currenttimestamp: Math.round(new Date() / 1000),
            page: that.data.lasttimestamp,
            count: that.data.count,
          },
          success: function(res) {
            console.log(res.data.data)
            let arr = that.data.dataList
            let lasttimestamp = that.data.lasttimestamp
            console.log(lasttimestamp)
            let pages = lasttimestamp + 1
            console.log(pages)
            let array = []
            that.setData({
              lasttimestamp: pages
            })
            if (res.data.data.length) {
              array = arr.concat(res.data.data)

              wx.showLoading({
                title: '加载中',
              })

              that.setData({
                dataList: array,

              }, () => {
                wx.hideLoading()
              })
            } else {
              wx.showToast({
                title: '到底了',
                icon: 'success',

              })
            }
          }
        })
      },
    });
  },
  share: function() {
    var that = this;
    Promise.all([
      promise1, promise2, promise3, promise4, promise5, promise6
    ]).then(res => {
      console.log(res)
      // if (!that.data.shareImage) {

      that.setData({
        isShow: true,
        issetting: false,
        isCanvas: true
      })
      wx.showLoading({
        title: '正在生成图片...',
        mask: true,
      });
      let yOffset = 0;
      const goodsTitle = that.data.activelist.title
      const goodscontent = that.data.activelist.content
      let goodsTitleArray = []
      let goodscontentArray = []
      //处理标题和内容过长
      for (let i = 0; i < goodsTitle.length / 17; i++) {
        if (i > 1) {
          break;
        }
        goodsTitleArray.push(goodsTitle.substr(i * 17, 17));
      }
      for (let i = 0; i < goodscontent.length / 20; i++) {
        if (i > 5) {
          break;
        }
        goodscontentArray.push(goodscontent.substr(i * 20, 20));
      }
      const content = that.data.activelist.content;
      canvasCtx = wx.createCanvasContext('shareCanvas');
      //绘制背景
      canvasCtx.drawImage(res[0], 0, 0, 300, 470);
      //绘制团长
      var avatarurl_width = 60; //绘制的头像宽度
      var avatarurl_heigth = 60; //绘制的头像高度
      var avatarurl_x = 120; //绘制的头像在画布上的位置
      var avatarurl_y = 5; //绘制的头像在画布上的位置
      canvasCtx.save();
      canvasCtx.beginPath();
      canvasCtx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
      canvasCtx.clip();
      canvasCtx.drawImage(res[1], avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
      canvasCtx.restore();
      canvasCtx.setFontSize(16);
      var tzName = that.data.tzInfo.name
      if (tzName.length > 8) {
        tzName = tzName.substr(0, 6)
      }
      var toleft = 150 - tzName.length * 8;
      canvasCtx.fillText(tzName, toleft, 95);
      // //绘制活动标题和内容
      yOffset = 100;
      canvasCtx.setFontSize(15);
      canvasCtx.setFillStyle('#333333');
      canvasCtx.setTextAlign('left');
      for (var i = 0; i < goodsTitleArray.length; i++) {
        canvasCtx.setFontSize(15);
        canvasCtx.fillText(goodsTitleArray[i], 17, 120 + i * 20);
      }
      for (var i = 0; i < goodscontentArray.length; i++) {
        canvasCtx.setFontSize(13);
        canvasCtx.setFillStyle('#999999');
        canvasCtx.fillText(goodscontentArray[i], 20, 155 + i * 20);
      }
      canvasCtx.drawImage(res[3], 20, 250, 80, 80);
      canvasCtx.drawImage(res[4], 110, 250, 80, 80);
      canvasCtx.drawImage(res[5], 200, 250, 80, 80);
      //绘制二维码
      canvasCtx.drawImage(res[2], 40, 365, 100, 100);
      return res;
    }).then(res => {
      console.log(res);
      if (res.length == 6) {
        setTimeout(function() {
          canvasCtx.draw(false, function() {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 750,
              height: 1175,
              destWidth: 3750,
              destHeight: 5875,
              canvasId: 'shareCanvas',
              success: function(res) {
                that.setData({
                  shareImage: res.tempFilePath,
                  issetting: true,
                  ShowshareImg: res.tempFilePath
                })
                wx.hideLoading();
              },
              fail: function(res) {
                wx.hideLoading();
                wx.showToast({
                  title: '错误，请稍后再试',
                })
              },
            })
          });
        }, 1200)
      }
    })
  },
  //获取是否授权相册权限
  handleSetting: function(e) {
    let that = this;
    // 对用户的设置进行判断，如果没有授权
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '若不打开授权，则无法将图片保存在相册中！',
        showCancel: false
      })
      that.setData({
        saveImgBtnHidden: true,
        openSettingBtnHidden: true
      })
    } else {
      that.setData({
        saveImgBtnHidden: false,
        openSettingBtnHidden: false,
        issetting: true
      })
      wx.showModal({
        title: '提示',
        content: '您已授权，赶紧将图片保存在相册中吧！',
        showCancel: false
      })
    }
  },
  //保存图片到相册
  SaveShareImg: function() {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.shareImage,
      success: function(res) {
        wx.showModal({
          title: '存图成功',
          content: '图片成功保存到相册了，去发朋友圈咯~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function(res) {
            if (res.confirm) {
              that.setData({
                isShow: false
              })
            }
          }
        })
      },
      fail: function(res) {
        if (res.errMsg != 'saveImageToPhotosAlbum:fail cancel') {
          wx.showModal({
            title: '授权提示',
            content: '请去授权，否则无法分享到朋友圈哦！',
            success: function(res) {
              if (res.cancel) {
                that.setData({
                  openSettingBtnHidden: false,
                  issetting: true
                })
              } else {
                //点击确定
                that.setData({
                  openSettingBtnHidden: true,
                  issetting: false
                })
              }
            },
            fail: function(res) {
              wx.showToast({
                title: '错误，请稍后再试',
              })
            }
          })
        }
      }
    })
  },
  //取消保存
  CancelShareImg: function() {
    this.setData({
      isShow: false
    })
  },
  goshare: function() {
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  onShareAppMessage: function() { //分享页面
    var tzInfo = JSON.stringify(wx.getStorageSync('tzInfo'));
    return {
      title: this.data.activelist.title,
      path: '/pages/jielong/products/products?activeid=' + this.data.id + "&activestatus=" + this.data.status + '&tzInfo=' + tzInfo,
      success: function(res) {
        console.log(res);
        console.log("转发成功:" + JSON.stringify(res));
      }
    }
  },
})